<template>
  <div class="order-detail-page">
    <!-- 顶部导航 -->
    <NavBar>
      <template #default>
        订单详情
      </template>
    </NavBar>

    <!-- 订单状态进度条 -->
    <div class="status-progress">
      <div class="progress-steps">
        <div
          v-for="(step, index) in statusSteps"
          :key="index"
          class="step"
          :class="{
            'active': step.status <= currentStatusStep,
            'current': step.status === currentStatusStep
          }"
        >
          <div class="step-icon">{{ step.status > currentStatusStep ? index + 1 : '✓' }}</div>
          <div class="step-label">{{ step.label }}</div>
        </div>
      </div>
    </div>

    <!-- 订单基本信息 -->
    <div class="order-info-card">
      <div class="info-item">
        <span class="label">订单编号</span>
        <span class="value">{{ order.orderId }}</span>
      </div>
      <div class="info-item">
        <span class="label">创建时间</span>
        <span class="value">{{ formatDate(order.updateTime) }}</span>
      </div>
      <div class="info-item">
        <span class="label">支付方式</span>
        <span class="value">{{ getPaymentMethod(order.paymentType) }}</span>
      </div>
      <div class="info-item" v-if="order.payTime">
        <span class="label">支付时间</span>
        <span class="value">{{ formatDate(order.payTime) }}</span>
      </div>
    </div>

    <!-- 收货信息 -->
    <div class="address-card" v-if="shippingAddress">
      <div class="address-header">
        <van-icon name="location-o" />
        <span>收货信息</span>
      </div>
      <div class="address-content">
        <div class="receiver">
          <span>{{ shippingAddress.receiverName }}</span>
          <span>{{ shippingAddress.receiverPhone }}</span>
        </div>
        <div class="address-detail">
          {{ shippingAddress.province }}{{ shippingAddress.city }}
          {{ shippingAddress.region }}{{ shippingAddress.detailAddress }}
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="goods-list-card">
      <div class="card-header">商品信息</div>
      <div class="goods-list">
        <div v-for="item in order.items" :key="item.orderItemId" class="goods-item">
          <img :src="item.productDTO.mainImage" class="goods-image">
          <div class="goods-info">
            <div class="goods-name">{{ item.productDTO.productName }}</div>
            <div class="goods-spec">{{ item.spec || '默认规格' }}</div>
            <div class="goods-price">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单金额信息 -->
    <div class="amount-card">
      <div class="amount-item">
        <span class="label">商品总价</span>
        <span class="value">¥{{ order.totalAmount.toFixed(2) }}</span>
      </div>
      <div class="amount-item">
        <span class="label">运费</span>
        <span class="value">¥{{ (order.shippingFee || 0).toFixed(2) }}</span>
      </div>
      <div class="amount-item" v-if="order.discountAmount">
        <span class="label">优惠</span>
        <span class="value">-¥{{ order.discountAmount.toFixed(2) }}</span>
      </div>
      <div class="amount-item total">
        <span class="label">实付金额</span>
        <span class="value">¥{{ (order.actualAmount || order.totalAmount).toFixed(2) }}</span>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="action-bar" v-if="order.orderStatus !== null && order.orderStatus !== undefined">
      <!-- 已取消状态 (0) -->
      <template v-if="order.orderStatus === 0">
        <button class="primary-btn" @click="reorder">重新购买</button>
      </template>

      <!-- 待付款状态 (1) -->
      <template v-else-if="order.orderStatus === 1">
        <button class="default-btn" @click="cancelOrder">取消订单</button>
        <button class="primary-btn" @click="payOrder">立即支付</button>
      </template>

      <!-- 待发货 (2) -->
      <template v-else-if="order.orderStatus === 2">
        <button class="default-btn" @click="contactCustomerService">联系客服</button>
        <button class="primary-btn" @click="showRefundDialog('onlyRefund')">申请退款</button>
      </template>

      <!-- 待收货 (3) -->
      <template v-else-if="order.orderStatus === 3">
        <button class="default-btn" @click="contactCustomerService">联系客服</button>
        <button class="default-btn" @click="showRefundDialog('refundAndReturn')">退货退款</button>
        <button class="primary-btn" @click="confirmReceipt">确认收货</button>
      </template>

      <!-- 待评价 (4) -->
      <template v-else-if="order.orderStatus === 4">
        <button class="default-btn" @click="goToAfterSale">申请售后</button>
        <button class="primary-btn" @click="goToReview">评价订单</button>
      </template>

      <!-- 退款/售后 (5) -->
      <template v-else-if="order.orderStatus === 5">
        <button class="default-btn" @click="contactCustomerService">联系客服</button>
        <button class="primary-btn" @click="viewAfterSaleProgress">查看进度</button>
      </template>

      <!-- 已完成 (7) -->
      <template v-else-if="order.orderStatus === 7">
        <button class="default-btn" @click="contactCustomerService">联系客服</button>
        <button class="primary-btn" @click="goToReview">评价订单</button>
      </template>

      <!-- 未知状态 -->
      <template v-else>
        <div class="unknown-status">
          未知订单状态: {{ order.orderStatus }}
        </div>
      </template>
    </div>

    <!-- 退款对话框 -->
    <van-dialog v-model:show="showRefund" title="申请退款" show-cancel-button @confirm="submitRefund">
      <div class="dialog-content">
        <van-field
          v-model="refundReason"
          label="退款原因"
          type="textarea"
          placeholder="请输入退款原因"
          rows="3"
          autosize
        />
        <van-field
          v-if="refundType === 'refundAndReturn'"
          v-model="returnTrackingNumber"
          label="退货物流单号"
          placeholder="请输入退货物流单号"
        />
      </div>
    </van-dialog>

    <!-- 取消订单确认对话框 -->
    <van-dialog
      v-model:show="showCancelConfirm"
      title="确认取消订单"
      message="确定要取消此订单吗？"
      show-cancel-button
      @confirm="confirmCancelOrder"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import { useOrderStore } from '@/stores/orderStore'
import { useAddressStore } from '@/stores/addressStore'
import { useUserStore } from '@/stores/userStore'

const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore()
const addressStore = useAddressStore()
const userStore = useUserStore()

const order = ref({
  orderId: '',
  userId: '',
  addressId: '',
  paymentType: 1,
  orderStatus: null,
  updateTime: '',
  itemCount: 0,
  totalAmount: 0,
  items: []
})

const isLoading = ref(false)
const showRefund = ref(false)
const refundType = ref('onlyRefund')
const refundReason = ref('')
const returnTrackingNumber = ref('')
const showCancelConfirm = ref(false)

// 订单状态步骤
const statusSteps = [
  { status: 1, label: '待付款' },
  { status: 2, label: '待发货' },
  { status: 3, label: '待收货' },
  { status: 4, label: '待评价' },
  { status: 5, label: '已完成' }
]

// 计算当前状态对应的进度步骤
const currentStatusStep = computed(() => {
  // 已完成状态(7)映射到已完成步骤(5)
  if (order.value.orderStatus === 7) return 5
  return order.value.orderStatus
})

// 计算收货地址
const shippingAddress = computed(() => {
  if (order.value.shippingAddress) {
    return order.value.shippingAddress
  }
  if (order.value.addressId && addressStore.addresses?.length) {
    return addressStore.addresses.find(
      addr => addr.addressId === order.value.addressId
    )
  }
  return null
})

// 初始化加载
onMounted(async () => {
  await fetchOrderDetail()
  if (!order.value.shippingAddress && userStore.userInfo?.userId) {
    await addressStore.fetchUserAddresses(userStore.userInfo.userId)
  }
  console.log('orderStatus:', order.value.orderStatus)
  console.log('order 对象:', order.value)
})

// 获取订单详情
const fetchOrderDetail = async () => {
  isLoading.value = true
  try {
    const orderId = route.params.id
    const orderData = await orderStore.fetchOrderDetail(orderId)

    if (orderData) {
      order.value = {
        ...orderData,
        orderStatus: Number(orderData.orderStatus) || null,
        addressId: orderData.addressId || null,
        totalAmount: orderData.totalAmount || 0
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    showToast('获取订单详情失败')
  } finally {
    isLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methods = {
    1: '支付宝',
    2: '微信支付',
    3: '银行卡'
  }
  return methods[method] || `未知支付(${method})`
}

// 取消订单
const cancelOrder = () => {
  showCancelConfirm.value = true
}

const confirmCancelOrder = async () => {
  try {
    await orderStore.cancelOrder(order.value.orderId)
    showToast('订单已取消')
    fetchOrderDetail()
  } catch (error) {
    console.error('取消订单失败:', error)
    showToast('取消订单失败')
  }
}

// 立即支付
const payOrder = () => {
  router.push(`/payment/${order.value.orderId}`)
}

// 重新购买
const reorder = async () => {
  try {
    showToast('商品已加入购物车')
    router.push('/cart')
  } catch (error) {
    console.error('重新购买失败:', error)
    showToast('重新购买失败')
  }
}

// 显示退款对话框
const showRefundDialog = (type) => {
  refundType.value = type
  refundReason.value = ''
  returnTrackingNumber.value = ''
  showRefund.value = true
}

// 提交退款申请
const submitRefund = async () => {
  try {
    const params = {
      orderId: order.value.orderId,
      reason: refundReason.value,
      type: refundType.value === 'onlyRefund' ? 1 : 2
    }

    if (refundType.value === 'refundAndReturn') {
      params.returnTrackingNumber = returnTrackingNumber.value
    }

    await orderStore.applyAfterSale(params)
    showToast('退款申请已提交')
    fetchOrderDetail()
  } catch (error) {
    console.error('提交退款申请失败:', error)
    showToast('提交退款申请失败')
  }
}

// 确认收货
const confirmReceipt = async () => {
  try {
    await orderStore.confirmReceipt(order.value.orderId)
    showToast('确认收货成功')
    fetchOrderDetail()
  } catch (error) {
    console.error('确认收货失败:', error)
    showToast('确认收货失败')
  }
}

// 联系客服
const contactCustomerService = () => {
  router.push({
    path: '/customer-service',
    query: {
      orderId: order.value.orderId,
      from: 'order-detail'
    }
  })
}

// 去评价
const goToReview = () => {
  router.push(`/review/${order.value.orderId}`)
}

// 申请售后
const goToAfterSale = () => {
  router.push(`/after-sale/apply/${order.value.orderId}`)
}

// 查看售后进度
const viewAfterSaleProgress = () => {
  router.push(`/after-sale/progress/${order.value.orderId}`)
}
</script>

<style scoped>
.order-detail-page {
  padding-bottom: 60px;
}

.status-progress {
  padding: 15px;
  background: #fff;
  margin-bottom: 10px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.progress-steps::before {
  content: '';
  position: absolute;
  top: 15px;
  left: 0;
  right: 0;
  height: 2px;
  background: #ebedf0;
  z-index: 1;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
}

.step-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #ebedf0;
  color: #969799;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
  font-size: 14px;
}

.step.active .step-icon {
  background: #1989fa;
  color: #fff;
}

.step.current .step-icon {
  border: 2px solid #1989fa;
}

.step-label {
  font-size: 12px;
  color: #969799;
}

.step.active .step-label {
  color: #1989fa;
}

.order-info-card,
.address-card,
.goods-list-card,
.amount-card {
  background: #fff;
  margin-bottom: 10px;
  padding: 15px;
}

.card-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item .label {
  color: #969799;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.address-header .van-icon {
  margin-right: 5px;
  color: #1989fa;
}

.receiver {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.address-detail {
  color: #323233;
  line-height: 1.5;
}

.goods-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f7f8fa;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  border-radius: 4px;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 14px;
  color: #323233;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-spec {
  font-size: 12px;
  color: #969799;
  margin: 5px 0;
}

.goods-price {
  font-size: 14px;
  color: #f44;
  text-align: right;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.amount-item.total {
  font-weight: bold;
  color: #f44;
}

.action-bar {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  /* display: flex; */
  justify-content: flex-end;
  padding: 10px 15px;
  background: #fff;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.05);
  display: flex !important; /* 强制显示 */
  z-index: 100; /* 确保不被其他元素遮挡 */
}

.default-btn {
  padding: 0 15px;
  height: 36px;
  line-height: 36px;
  border: 1px solid #ebedf0;
  border-radius: 18px;
  background: #fff;
  color: #323233;
  margin-right: 10px;
}

.primary-btn {
  padding: 0 15px;
  height: 36px;
  line-height: 36px;
  border: none;
  border-radius: 18px;
  background: #1989fa;
  color: #fff;
}

.dialog-content {
  padding: 15px;
}

/* 新增退款对话框样式 */
.dialog-content {
  padding: 15px;
}

.dialog-content .van-field {
  margin-bottom: 15px;
  background: #f7f8fa;
  border-radius: 8px;
  padding: 10px 12px;
}

.dialog-content .van-field--textarea {
  min-height: 100px;
}

.dialog-content .van-field__label {
  color: #323233;
  font-weight: 500;
}

.dialog-content .van-field__control {
  color: #323233;
}

/* 确保对话框标题样式 */
:deep(.van-dialog__header) {
  padding-top: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>